import React, { useState,useEffect } from 'react';
import { Table, Button, Space, Tag, Modal, message } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, LockOutlined  } from '@ant-design/icons';
import UserForm from './components/UserForm';
import PasswordForm from './components/PasswordForm';
import { userStore } from './store/userStore';
import { User } from './store/userTypes';
import { observer } from 'mobx-react-lite';

const UserList: React.FC = observer(() => {
  useEffect(() => {
    userStore.getActiveRole();
    userStore.getActiveUser();
    userStore.fetchUsers();
  }, []);


  const getRoleNameTag = (roleId: string) => {
    const roleMap = userStore.roleValues;
    const config = roleMap && roleMap[roleId as keyof typeof roleMap];
      return config ? <Tag color={config.color}>{config.title}</Tag> : null;
  };

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isPwdModalVisible, setIsPwdModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [modalType, setModalType] = useState<'create' | 'edit' | 'view'>('create');

  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '真实姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '角色',
      dataIndex: 'roleId',
      key: 'roleId',
      render: (roleId: string) => getRoleNameTag(roleId),
    },
    // {
    //   title: '职位',
    //   dataIndex: 'position',
    //   key: 'position',
    // },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === 'active' ? 'success' : 'error'}>
          {status === 'active' ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: User) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
            <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleReset(record)}
          >
            重置密码
          </Button>
          <Button
            type="link"
            danger
            disabled={record.username==='admin' || record.username==='sysadmin'}
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleCreate = () => {
    setModalType('create');
    setEditingUser(null);
    setIsModalVisible(true);
  };

  const handleBatchPwd = () => {
    setModalType('create');
    setIsPwdModalVisible(true);
  };

  const handleEdit = (record: User) => {
    setModalType('edit');
    getUser(record);
  };

  const handleReset = (record: User) => {
    resetPwd(record);
  };

  const resetPwd = async (record: User) => {
    try {
      await userStore.resetPwd(record.id);
    } catch (error) {
      console.error('重置密码失败:', error);
      message.error('重置密码失败');
    }
  };

  const handleView = (record: User) => {
    setModalType('view');
    getUser(record);
  };

  const getUser = async (record: User) => {
    try {
      const userData = await userStore.getUser(record.id);
      setEditingUser(userData); // 使用返回的用户数据
      setIsModalVisible(true);
    } catch (error) {
      console.error('获取用户详情失败:', error);
      message.error('获取用户详情失败');
    }
  };

  const handleDelete = (record: User) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除用户 ${record.username} 吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        userStore.deleteUser(record.id);
        message.success('删除成功');
      },
    });
  };

  const handleModalClose = () => {
    setIsModalVisible(false);
    setEditingUser(null);
  };

  const handlePdwModalClose = () => {
    setIsPwdModalVisible(false);
  };

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Space>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleCreate}
          >
            新建用户
          </Button>
          
          <Button
            type="default"
            icon={<LockOutlined />}
            onClick={handleBatchPwd} // 确保使用正确的处理函数
          >
            修改密码
          </Button>
        </Space>
      </div>

      <Table
        columns={columns}
        dataSource={Array.isArray(userStore.users) ? userStore.users : []}
        rowKey="id"
        loading={userStore.loading}
        locale={{ emptyText: '暂无数据' }}
      />

      <Modal
        title={
          modalType === 'create'
            ? '新建用户'
            : modalType === 'edit'
            ? '编辑用户'
            : '查看用户'
        }
        open={isModalVisible}
        onCancel={handleModalClose}
        footer={null}
        width={800}
        destroyOnClose
      >
        <UserForm
          type={modalType}
          initialValues={editingUser}
          onCancel={handleModalClose}
        />
      </Modal>

      <Modal
        title='修改密码'
        open={isPwdModalVisible}
        onCancel={handlePdwModalClose}
        footer={null}
        width={600}
        destroyOnClose
      >
        <PasswordForm
          type='create'
          initialValues={null}
          onCancel={handlePdwModalClose}
        />
      </Modal>

    </div>
  );
});

export default UserList; 